package hqyj.example.seata_user.service.impl;

import hqyj.example.seata_user.entity.User;
import hqyj.example.seata_user.mapper.UserMapper;
import hqyj.example.seata_user.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void debit(int userId, int money) {
        Optional<User> byId = Optional.ofNullable(userMapper.selectById(userId));
        if(byId.isPresent()) {
            User user = byId.get();
            if(user.getMoney() >= money) {
                // 减余额
                user.setMoney(user.getMoney() - money);
                //userMapper.insert(user);
                userMapper.updateById(user);
            }
            else {
                throw new RuntimeException("该用户余额不足！");
            }
        }
        else {
            throw new RuntimeException("没有该用户！");
        }
    }
}
